package com.trgis.zhejiangimg;

import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.time.*;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * 2024/6/12
 * 鉴权的方法类
 * @author fengyu
 */
public class SignatureZheJiang implements Signature{
    final Logger log = LoggerFactory.getLogger(SignatureZheJiang.class);
    // 替换自己申请的ak
    @Value("${accessKey}")
    String accessKey = "514e7c54f2484395ac333d8b3ba789a";
    // 替换自己申请的sk
    @Value("${secretKey}")
    String secretKey = "cd1bc2d14ab44f4ca2ebc86d9297d0d";

    private long limitLong;

    private String signatureStr;

    private String formatStr(String str){
        return str.replaceAll("=*$", "")
                .replaceAll("\\+","-")
                .replaceAll("/","_");
    }

    /**
     * 有效期1个小时 *
     */
    private String payload(){
        limitLong = Instant.now().toEpochMilli();

        StringBuilder sb = new StringBuilder("{\"key\":\"")
                .append(accessKey).append("\",\"exp\":");
        LocalDateTime l = LocalDateTime.of(LocalDate.now(), LocalTime.now().withHour(LocalTime.now().getHour()+ 1));
        return sb.append(l.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()).append("}").toString();
    }

    private String beforeSign(){
        String header = """
                {"alg":"HS256","typ":"JWT"}""";
        String head = Base64.getEncoder().encodeToString(header.getBytes(StandardCharsets.UTF_8));
        String pay = Base64.getEncoder().encodeToString(payload().getBytes(StandardCharsets.UTF_8));
        return formatStr(head) + "." + formatStr(pay);
    }

    /**
     * 因在一个小时内，所以判断超过50分钟就重新生成一个 *
     */
    private String finalSignatrue() throws Exception {
        long offset = 50 * 60 * 1000;
        if (null == signatureStr || Instant.ofEpochMilli(limitLong + offset).isAfter(Instant.now())) {
            String beforeSign = beforeSign();

            // 创建HmacSHA256 Mac实例
            Mac sha256_HMAC =  Mac.getInstance("HmacSHA256");
            // 使用密钥初始化Mac实例
            SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
            sha256_HMAC.init(secret_key);
            // 执行HMAC操作
            byte[] hash = sha256_HMAC.doFinal(beforeSign.getBytes(StandardCharsets.UTF_8));
            // 将字节数组转换为Base64编码的字符串
            String signature = formatStr(Base64.getEncoder().encodeToString(hash));
//            log.info("sinnature: {}", signature);
            signatureStr = beforeSign + "." + signature;
        }
        return signatureStr;

    }


    @Override
    public String signatrue() throws Exception {
        return signatureStr = "jwt=" + finalSignatrue() + "&x-bg-auth-type=jwt_auth";
    }

    @Override
    public List<NameValuePair> Signatrue() throws Exception {
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        nameValuePairs.add(new BasicNameValuePair("jwt", finalSignatrue()));
        nameValuePairs.add(new BasicNameValuePair("x-bg-auth-type","jwt_auth"));
        return nameValuePairs;
    }
}
